<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * Redis 服务器    
 */
class RedisServiceController
{
    private static $instance = null;
    private $redis = null;

    /**
     * 初始化redis服务
     */
    private function __construct()
    {
        $this->redis = new \Redis();
        $res = $this->redis->pconnect(config('redis.host'), config('redis.port'));
        if (true === $res) {
            if (true === $this->redis->auth(config('redis.password'))) {
                $db = config('redis.database');
                $this->redis->select($db);

              //  Log::info('初始化redis服务成功 -> ' . config('redis.host') . ':' . config('redis.port'));
            } else {
                Log::error('初始化redis服务失败 -> 验证失败');
                $redis = null;
            }
        } else {
            Log::error('初始化redis服务失败 -> ' . config('redis.host') . ':' .  config('redis.port'));
        }
    }

    private function __clone()
    {
    }


    /**
     * 设置某个值
     * @param $name  字段名
     * @param $value  字段值
     * @param $expire_time  过期时间  单位秒
     */
    public function setRedisValue($name, $value, $expire_time = 0)
    {
        return $this->redis->setex($name, $expire_time, $value); //重新设置过期时间
    }

    /**
     * 获取某个值
     */
    public function getRedisValue($name)
    {
        return $this->redis->get($name);
    }

    /**
     * 删除某个值
     * $name
     */
    public function delRedisValue($name)
    {
        if ($this->redis->exists($name)) {
            $this->redis->del($name);
        }
        return true;
    }

    /**
     * 判断某个字段值支付存在
     * $name
     */
    public function valueExists($name)
    {
        if ($this->redis->exists($name)) {
            return true;
        }
        return false;
    }

    public static function getInstance(): RedisServiceController
    {
        if (null == self::$instance) {
           // Log::info("init...");
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function getRedis(): \Redis
    {
        return $this->redis;
    }
}
